package servlet.hedong;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import pojo.BackMessage;
import pojo.FontMessage;
import service.BackMessageService;
import service.FontMessageService;
import service.UserService;
import service.impl.BackMessageServiceImpl;
import service.impl.FontMessageServiceImpl;
import service.impl.UserServiceImpl;
import util.PageBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * 前台消息首页数据接口
 * @author 何栋
 **/
@WebServlet(value = "/fontMessageHome")
public class MessageHomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Object userId = session.getAttribute("session");//用户id
          String uId=  userId.toString();//用户ID的String格式
        BackMessageService backMessageService=new BackMessageServiceImpl();
        FontMessageService messageService=new FontMessageServiceImpl();//为调用服务层方法做准备
        String operate=req.getParameter("operate");//operate为操作类型
        String state=req.getParameter("state");//获取邮件状态参数
        String data=req.getParameter("data");//获取邮件内容
        String sendReceive=req.getParameter("sendReceive");//发件箱或收件箱
        String email=req.getParameter("email");
        int stateInt=3;
        if ("update".equals(operate)){//operate为update时执行更新操作
            String messageId=req.getParameter("messageId");//获取消息id--messageId
            String[] messageIdArray=messageId.split(",");//messageId在jsp页面中为数组，此处重新将其转换为数组
            int[] messageIdInt=new int[messageIdArray.length];
            stateInt=Integer.parseInt(state);
            for (int i=0;i<messageIdArray.length;i++){

                messageIdInt[i]=Integer.parseInt(messageIdArray[i]);
            }
            int result=messageService.modifyState(messageIdInt,stateInt);
            if (result>0){
                req.getRequestDispatcher("jsp/hd/home.jsp").forward(req,resp);
            }else {
                System.out.println("提交失败");
            }
        }else if ("delete".equals(operate)){
            String messageId=req.getParameter("messageId");
            if (null!=messageId){
               int result= messageService.deletOne(Integer.parseInt(messageId));
                if (result>0){//如果删除成功则转回首页
                    req.getRequestDispatcher("jsp/hd/home.jsp").forward(req,resp);
                }else{//否则转到提示页面
                    req.setAttribute("result",result);
                    req.getRequestDispatcher("jsp/hd/alertPage.jsp").forward(req,resp);
                }

            }else{
                int result=0;
                req.setAttribute("result",result);
                req.getRequestDispatcher("jsp/hd/alertPage.jsp").forward(req,resp);
            }
        }else if ("add".equals(operate)){
            String message=req.getParameter("message");
            String title=req.getParameter("title");
            BackMessage backMessage=new BackMessage();
            FontMessage fontMessage=new FontMessage();
            fontMessage.setMessage(message);
            backMessage.setMessage(message);
            UserService userService=new UserServiceImpl();
            int receiveIserId=userService.queryOne(email);
            System.out.println(email);
            if (null!=uId){

                fontMessage.setUId(Integer.parseInt(uId));//发邮件
                backMessage.setUId(receiveIserId);//收邮件
            }else {
                System.out.println("用户ID为空");
            }
            fontMessage.setTitle(title);
            backMessage.setTitle(title);
            fontMessage.setSendReceive(1);//发邮件
            backMessage.setSendReceive(0);//收邮件
          int result=  messageService.addOne(fontMessage,backMessage);
            req.setAttribute("result",result);
            req.getRequestDispatcher("jsp/hd/alertPage.jsp").forward(req,resp);

        }else if ("select".equals(operate)){
            PageBean pageBean=new PageBean();//未获取分页信息做准备

            stateInt=3;//stateInt用于接收邮件状态参数，初始值为3（不为0-未读、1-已读），查询所有
            int sendReceiveInt=3;
            if (null!=sendReceive&&""!=sendReceive){
                sendReceiveInt=Integer.parseInt(sendReceive);
            }

            if (null!=state&&""!=state){
                stateInt=Integer.parseInt(state);
            }
            PrintWriter out = resp.getWriter();

            String page=req.getParameter("page");//当前页
            String limits=req.getParameter("limit");//每页显示数据条数
            pageBean.setPageIndex(Integer.parseInt(page));//设置当前页数
            pageBean.setPageSize(Integer.parseInt(limits));//设置每页显示数据条数
            JSONObject json=new JSONObject();
            json.put("code",0);
            json.put("msg","");
            List<Map> map = messageService.turnPageTitle(pageBean, stateInt,Integer.parseInt(uId),sendReceiveInt);//调用分页方法，分页信息在此设置
            int count=  pageBean.getTotalCount();//获取分页信息的数据总数
            json.put("count",count);
            json.put("data", JSONArray.fromObject(map));

            out.print(json);//将需要展示的信息发送到前台
        }else if ("catEmailContent".equals(operate)){
            JSONArray array=   JSONArray.fromObject(data);
            req.setAttribute("content",array);
            System.out.println(req.getParameter("content"));
            req.getRequestDispatcher("/jsp/hd/MessageContent.jsp").forward(req,resp);
        }

    }
}
